package com.validated.constraint;

import com.validated.annotation.Digits;
import com.validated.annotation.NotNull;
import com.validated.annotation.Phone;
import java.lang.annotation.Annotation;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 注解处理器初始化
 *
 * @author Moo
 * @date 2023/05/11
 */
public class ConstraintRegister {

    private static Map<Class<? extends Annotation>, ConstraintValidator> constraintMap = new ConcurrentHashMap<>();


    static {
        constraintMap.put(NotNull.class, newInstance(NotNullConstraint.class));
        constraintMap.put(Phone.class, newInstance(PhoneConstraint.class));
        constraintMap.put(Digits.class, newInstance(DigitsConstraint.class));
    }

    public static ConstraintValidator newInstance(Class<? extends ConstraintValidator> constraint){
        try {
            return constraint.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 是否已注册
     *
     * @param constraintType 约束类型
     * @return boolean
     */
    public static boolean isRegistered(Class<? extends Annotation> constraintType) {
        return constraintMap.containsKey(constraintType);
    }

    /**
     * 得到约束处理器
     *
     * @param constraintType 约束类型
     * @return {@link ConstraintValidator}
     */
    public static ConstraintValidator getConstraint(Class<? extends Annotation> constraintType) {
        if (constraintMap.containsKey(constraintType)) {
            return constraintMap.get(constraintType);
        }
        return null;
    }
}
